package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.service.ApUserRealnameService;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;

/**
 * @version 1.0
 * @description <p>APP实名认证信息 业务实现</p>
 * @package com.itheima.user.service.impl
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ApUserMapper apUserMapper;
    private ApUserRealnameMapper apUserRealnameMapper;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Override
    public PageResultVo pageList(ApUserRealnamePageRequestDto dto) {

        LambdaQueryWrapper<ApUserRealname> lqw = new LambdaQueryWrapper<>();
        IPage<ApUserRealname> page = new Page();
        page.setSize(dto.getSize());
        page.setPages(dto.getPage());
        lqw.eq(!StringUtils.isEmpty(dto.getStatus()), ApUserRealname::getStatus, dto.getStatus());
        IPage<ApUserRealname> iPage = page(page, lqw);
        return PageResultVo.pageResult(iPage.getPages(), iPage.getSize(), iPage.getTotal(), iPage.getRecords());
    }

    //驳回功能实现
    @Override
    public void reject(HashMap<String, Object> map) {
//        查询这一条id的值  然后将状态进行改变  时间进行改变
        Integer id = (Integer) map.get("id");
        String msg = (String) map.get("msg");
//       更新  非空判断
        if (id == null || StringUtils.isEmpty(msg)) {
            throw new LeadNewsException(HttpCodeEnum.PARAM_INVALID);
        }
        ApUserRealname realname = new ApUserRealname();
        realname.setUpdatedTime(LocalDateTime.now());
        realname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        realname.setReason(msg);
        realname.setId(id.longValue());
        updateById(realname);
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void pass(HashMap<String, Object> map) {
        Integer id = (Integer) map.get("id");
        if (null == id) {
            throw new LeadNewsException("id不能为空");
        }
//        首先更新  user_realName表
        updateByIdRealName(id);

        ApUserRealname byId = getById(id);
//        社交账号进行查询
        Long userId1 = byId.getUserId();
//        这里应该是我的id  并不应该用上面的只是巧合
        ApUser apUser = apUserMapper.selectById(id.longValue());
//        添加自媒体人账号
        Long wmUserId = addWmUser(apUser);  //得到id
//        添加作者账号
        addApAuthor(apUser, wmUserId);
//        更新用户表当中的信息
        updateUserFlag(userId1);
    }

    private void updateUserFlag(Long userId1) {
        ResultVo<WmUser> resultVo = wmUserFeign.getByApUserId(userId1);
//        对结果进行解析
        ApUser apUser = apUserMapper.selectById(userId1);
        apUser.setId(userId1);
        apUser.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        apUserMapper.updateById(apUser);
    }

    private void updateByIdRealName(Integer id) {
        //        得到userId  这个与user_id的相同  更新真实信息表
        ApUserRealname realname = new ApUserRealname();
//        更新user_realName表  设置状态为人工审核通过  通过id进行更新
        realname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        realname.setUpdatedTime(LocalDateTime.now());
        realname.setId(id.longValue());
        updateById(realname);
    }
//需要wmuser_id对应作者然后进行更新  纽带
    private void addApAuthor(ApUser apUser, Long wmUserId) {
//        更新作者表信息  添加一个作者的信息  根据这两个信息得到数据
        ResultVo<ApAuthor> getResult = apAuthorFeign.getByApUserAndWmUserId(apUser.getId(), wmUserId);
        if (!getResult.isSuccess()) {
            log.error("远程调用文章微服查询失败,{},{},{}", apUser.getId(), wmUserId, getResult.getErrorMessage());
            throw new LeadNewsException("远程调用文章微服查询失败");
        }
        ApAuthor author = getResult.getData();
//        为空时进行添加  可能已经存在
        if (author == null) {
            author = new ApAuthor();
            author.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
            author.setName(apUser.getName());
            author.setUserId(apUser.getId());
            author.setCreatedTime(LocalDateTime.now());
            author.setWmUserId(wmUserId);
//            更新作者表
            ResultVo resultVo = apAuthorFeign.addApAuthor(author);
            if (!resultVo.isSuccess()) {
                log.error("远程调用文章微服添加作者失败,{},{},{}", apUser.getId(), wmUserId, getResult.getErrorMessage());
                throw new LeadNewsException("远程调用文章微服添加作者失败");
            }

        }


    }

    /**
     * 添加自媒体账号
     *
     * @param
     * @param appUserInfo
     * @return
     */
    private Long addWmUser(ApUser appUserInfo) {
        ResultVo<WmUser> wmUserResult = wmUserFeign.getByApUserId(appUserInfo.getId());

        if (!wmUserResult.isSuccess()) {
            throw new LeadNewsException("调用自媒体微服务失败");
        }
        WmUser wmUser = wmUserResult.getData();
        // 4.2 如果不存在添加
        if (null == wmUser) {
            //4.3 创建自媒体账号
            wmUser = new WmUser();
//            拷贝公共字段
            BeanUtils.copyProperties(appUserInfo, wmUser);
//            将id重置
            wmUser.setId(null);
            wmUser.setApUserId(appUserInfo.getId());
            wmUser.setNickname(appUserInfo.getName());
            wmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
            wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
            wmUser.setCreatedTime(LocalDateTime.now());
            ResultVo<WmUser> insertResult = wmUserFeign.addWmUser(wmUser);
            if (!insertResult.isSuccess()) {
                // 添加自媒体失败了
                throw new LeadNewsException("调用自媒体微服务添加账号失败");
            }
            // 为什么
            wmUser = insertResult.getData();
        }
        return wmUser.getId();
    }
//        ResultVo<WmUser> apUserId = wmUserFeign.getByApUserId(appUserInfo.getId());
////       不成功的时候抛出异常
//        if (apUserId.isSuccess()) {
//            throw new LeadNewsException("调用自媒体微服务失败");
//        }
////        如果结果不是失败的话就创建对象
//        WmUser wmUser = new WmUser();
////        将基本属性进行拷贝
//        if (null == wmUser) {
//            BeanUtils.copyProperties(appUserInfo, wmUser);
//            wmUser.setId(null);
//            wmUser.setNickname(appUserInfo.getName());
//            wmUser.setApUserId(appUserInfo.getId());
//            wmUser.setLocation(null);
//            wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
//            wmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
//            wmUser.setCreatedTime(LocalDateTime.now());
////      添加对象
//            ResultVo<WmUser> wmUserResultVo = wmUserFeign.addWmUser(wmUser);
//            if (!wmUserResultVo.isSuccess()) {
//                throw new LeadNewsException("调用自媒体微服务失败");
//            }
////                解析结果
//            wmUser = wmUserResultVo.getData();
//        }
//        return wmUser.getId();
//    }


}
